package cn.panda.edu.controller;


import cn.panda.edu.model.Courseware;
import cn.panda.edu.service.StudentResourceService;
import cn.panda.edu.util.FileUtil;
import cn.panda.edu.util.ResultDataUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/student/")
public class StudentResourceController {
	@Autowired
	private StudentResourceService studentResourceService ;
	
	@ApiOperation(value="获取所有资源文件" , notes="")//用以指明api名称 
	@ApiImplicitParam(name="pageIndex", value="当前页数", required=true, dataType="int", paramType="form")  
	@RequestMapping(value = "/listResource", method = RequestMethod.POST)
	public Object listResource(Integer pageIndex, String coursewareName, String coursewareAddtime) throws ParseException {
		Date addDate = null ;
		if (coursewareAddtime != null && ! "".equals(coursewareAddtime)) {
			SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd") ;
			addDate = sdf.parse(coursewareAddtime) ;
		}
		Map<String, Object> condition = new HashMap<String, Object>() ;
		condition.put("fileName", coursewareName) ;
		condition.put("addDate", addDate) ;
		return ResultDataUtil.resData(200, "", studentResourceService.listResources(pageIndex, condition)) ;
	}
	
	@ApiOperation(value="学生端下载资源文件" , notes="")//用以指明api名称 
	@ApiImplicitParam(name="coursewareId", value="资源id", required=true, dataType="int", paramType="form")  
	@RequestMapping(value = "/downResource", method = RequestMethod.POST)
	public Map<String, Object> downloadResource(@RequestParam("coursewareId") Integer id, HttpServletResponse response)  {
		Courseware courseware= studentResourceService.getResource(id) ;
		String filePath = courseware.getCoursewarePath() ;
		int  status=200;
		String message=null;
		try {  
            FileUtil.downloadFile(filePath, courseware.getCoursewareName(), response);
            status=200;
            message="下载成功";
        } catch (Exception e) {
        	status=500;
            message="下载失败";
            e.printStackTrace();  
        }  
		return ResultDataUtil.resData(status, message, null) ;
	}
	
	
}









